﻿using System;
using System.Collections;
using System.Web;
using System.Web.Compilation;
using visinia.SmartEngine.Installer;
using visinia.SmartEngine.Site;

namespace visinia.SmartEngine
{
    /// <summary>
    /// visinia main url rewriter
    /// </summary>
    internal class UrlRewriter : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        #endregion

        private void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication httpApp = (HttpApplication)sender;
            HttpContext context = httpApp.Context;
            string url = context.Request.Url.AbsolutePath.ToLower();
            string actual = HandleURL(url, context, httpApp);
            if (string.IsNullOrEmpty(actual))
                return;
            context.RewritePath(actual);
        }

        private string HandleURL(string url, HttpContext context, HttpApplication httpApp)
        {
            string root = WebRoots.GetRelativeWebRoot;
            string rel = url.Remove(0, root.Length);
            string[] segments = rel.Split('/');
            IEnumerator enu = segments.GetEnumerator();
            enu.MoveNext();
            switch (((string)enu.Current).ToLower())
            {
                case "default.aspx":
                    return HandleDefaultPage(context, root);
                case "designer.aspx":
                    return HandleDesignerPage(context, root);
                case "install.aspx":
                    return root + "install.aspx";
            }
            string urlSeparator = TrimExtension((string)enu.Current).ToLower();
            {
                // find a plugin which will handle this urlSeparator urls
                Plugin plugin = PluginController.GetInstalledPlugins().Find(p => (string.Compare(p.UrlSeparator, urlSeparator, true) == 0));
                if (plugin != null)
                {
                    if (!string.IsNullOrEmpty(plugin.UrlRewriteController))
                    {                        
                        Type type = BuildManager.GetType(plugin.UrlRewriteController, false, true);
                        BaseUrlRewriter urlRewriter = (BaseUrlRewriter)Activator.CreateInstance(type);
                        return urlRewriter.RewriteUrl(httpApp, enu);
                    }
                }                
            }            
            return url;
        }

        private static string HandleDefaultPage(HttpContext context, string root)
        {
            // show front page on default.aspx            
            if (context.Request.QueryString["PageId"] == null) //Show Front page
                return root + "Default.aspx?PageId=" + SiteSettings.FrontPage;
            else
                return root + "Default.aspx?PageId=" + context.Request.QueryString["PageId"];
        }

        private static string HandleDesignerPage(HttpContext context, string root)
        {
            if (context.Request.QueryString["PageId"] == null) //Show Front page
                return root + "Designer.aspx?PageId=" + SiteSettings.FrontPage;
            else
                return root + "Designer.aspx?PageId=" + context.Request.QueryString["PageId"];
        }

        private static string TrimExtension(string url)
        {
            if (url.EndsWith(".aspx"))
                return url.Remove(url.LastIndexOf('.'));
            else
                return url;
        }
    }
}
